package info.mrchen.gae.weibo2mail.controller;

import info.mrchen.gae.weibo2mail.dao.TwitterWeiboDao;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@Controller
public class TwitterWeiboController {

    UserService userService = UserServiceFactory.getUserService();

    Twitter twitter = new TwitterFactory().getInstance();
    @Autowired
    TwitterWeiboDao twitterWeiboDao;

    @RequestMapping("/weibo/TwitterAdd.do")
    public void addAccount(HttpServletRequest request, HttpServletResponse response) {
        try {
            StringBuffer callbackURL = request.getRequestURL();
            int index = callbackURL.lastIndexOf("/");
            callbackURL.replace(index, callbackURL.length(), "").append("/TwitterCallback.do");
            RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
            request.getSession().setAttribute("TWITTER_REQUESTTOKEN", requestToken);
            response.sendRedirect(requestToken.getAuthenticationURL());
        } catch (TwitterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/weibo/TwitterCallback.do")
    public void callback(HttpServletRequest request, HttpServletResponse response) {
        RequestToken requestToken = (RequestToken) request.getSession().getAttribute("TWITTER_REQUESTTOKEN");
        String verifier = request.getParameter("oauth_verifier");
        try {
            AccessToken accessToken4Twitter = twitter.getOAuthAccessToken(requestToken, verifier);
            twitterWeiboDao.saveAccessToken(accessToken4Twitter, userService.getCurrentUser());
            request.getSession().removeAttribute("TWITTER_REQUESTTOKEN");
            response.sendRedirect("Welcome.do");
        } catch (TwitterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
